import yaml
import operator

class RuleEngine:
    OPERATORS = {
        '==': operator.eq,
        '!=': operator.ne,
        '<': operator.lt,
        '<=': operator.le,
        '>': operator.gt,
        '>=': operator.ge,
        'in': lambda x, y: x in y,
        'not in': lambda x, y: x not in y
    }
    
    def __init__(self, config_path):
        with open(config_path, 'r') as file:
            self.rules = yaml.safe_load(file)
    
    def evaluate(self, data):
        return self._evaluate_node(self.rules, data)
    
    def _evaluate_node(self, node, data):
        # print(f"Evaluating node: {node}")  # 添加调试信息
        if 'condition' in node:
            return self._evaluate_condition_node(node['condition'], data)
        elif 'all' in node:
            return self._evaluate_all_node(node['all'], data)
        elif 'any' in node:
            return self._evaluate_any_node(node['any'], data)
        elif 'branch' in node:
            return self._evaluate_branch_node(node['branch'], data)
        elif 'switch' in node:
            return self._evaluate_switch_node(node['switch'], data)
    
    def _evaluate_condition_node(self, node, data):
        # print(f"Evaluating condition node: {node}")  # 添加调试信息
        if 'field' not in node or 'operator' not in node or 'value' not in node:
            raise ValueError(f"Condition node must contain 'field', 'operator', and 'value'. Current node: {node}")
        field = node['field']
        value = data.get(field, None)
        operator_func = RuleEngine.OPERATORS[node['operator']]
        result = operator_func(value, node['value'])
        # print(f"Evaluating condition: {field} {node['operator']} {node['value']} with data value {value} -> {result}")
        return result
    
    def _evaluate_all_node(self, nodes, data):
        return all(self._evaluate_node(node, data) for node in nodes)
    
    def _evaluate_any_node(self, nodes, data):
        return any(self._evaluate_node(node, data) for node in nodes)
    
    def _evaluate_branch_node(self, node, data):
        if self._evaluate_node(node['condition'], data):
            return self._evaluate_node(node['then'], data)
        else:
            return self._evaluate_node(node['else'], data)
    
    def _evaluate_switch_node(self, node, data):
        # print(f"Evaluating switch node: {node}")  # 添加调试信息
        field = node['field']
        field_value = data.get(field, None)
        for case in node['cases']:
            if case['value'] == field_value:
                return self._evaluate_node(case['then'], data)
        if 'default' in node:
            return self._evaluate_node(node['default'], data)
        return False
